<template>
  <CommonLayout
    pageTitle="浏览历史"
    sidebarTitle="筛选条件"
    :showSidebar="true"
    :loading="loading"
    :isEmpty="products.length === 0 && !loading"
    emptyText="暂无浏览历史"
  >
    <!-- 侧边栏筛选内容 -->
    <template #sidebar>
      <form class="filter-form" @submit.prevent="handleFilter">
        <div class="filter-item">
          <label>搜索商品</label>
          <input
            type="text"
            placeholder="输入商品名称或关键词"
            v-model="filterForm.keyword"
            class="filter-input"
          />
        </div>

        <div class="filter-item">
          <label>商品分类</label>
          <select v-model="filterForm.categoryId" class="filter-select" @change="handleCategoryChange">
            <option value="">全部分类</option>
            <option v-for="category in allCategories" :key="category.category_id" :value="category.category_id">{{ category.name }}</option>
          </select>
        </div>

        <div class="filter-item">
          <label>浏览时间</label>
          <select v-model="filterForm.timeRange" class="filter-select">
            <option value="all">全部时间</option>
            <option value="today">今天</option>
            <option value="week">最近一周</option>
            <option value="month">最近一个月</option>
            <option value="quarter">最近三个月</option>
          </select>
        </div>

        <div class="filter-item">
          <label>时间排序</label>
          <select v-model="filterForm.sortByTime" class="filter-select">
            <option value="">默认排序</option>
            <option value="view_time_asc">浏览时间正序</option>
            <option value="view_time_desc">浏览时间倒序</option>
          </select>
        </div>

        <div class="filter-item">
          <label>价格范围</label>
          <div class="price-range">
            <input
              type="number"
              placeholder="最低价格"
              v-model="filterForm.minPrice"
              class="price-input"
            />
            <span>-</span>
            <input
              type="number"
              placeholder="最高价格"
              v-model="filterForm.maxPrice"
              class="price-input"
            />
          </div>
        </div>

        <div class="filter-item">
          <label>价格排序</label>
          <select v-model="filterForm.sortByPrice" class="filter-select">
            <option value="">默认排序</option>
            <option value="price_asc">价格从低到高</option>
            <option value="price_desc">价格从高到低</option>
          </select>
        </div>

        <button type="submit" class="filter-btn">应用筛选</button>
        <button
          type="button"
          class="reset-btn"
          @click="resetFilter"
        >
          重置筛选
        </button>
      </form>
    </template>

    <!-- 主内容区 -->
    <template #content>
      <div class="product-table-container" v-if="products.length > 0">
        <table class="product-table">
          <thead>
            <tr>
              <th>商品名称</th>
              <th>价格</th>
              <th>分类</th>
              <th>浏览时间</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in products" :key="item.history_id || item.product_id" class="product-row">
              <td>{{ item.title || '未命名商品' }}</td>
              <td>¥{{ formatPrice(item.price !== undefined ? item.price : 0) }}</td>
              <td>{{ item.category_name || '未分类' }}</td>
              <td>{{ formatDate(item.view_time) }}</td>
              <td>
                <span :class="['status-tag', item.status === 1 ? 'status-active' : item.status === 0 ? 'status-pending' : item.status === 2 ? 'status-sold' : item.status === 3 ? 'status-inactive' : 'status-inactive']">
                  {{ item.status === 0 ? '审核' : item.status === 1 ? '在售' : item.status === 2 ? '已售' : item.status === 3 ? '下架' : '未知' }}
                </span>
              </td>
              <td class="action-buttons">
                <button
                  class="btn-common btn查看"
                  @click="viewProductDetail(Number(item.product_id), item.status !== undefined ? item.status : 0)"
                  :disabled="item.status !== undefined && item.status !== 1"
                >
                  查看详情
                </button>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <div class="pagination-info">
            共 {{totalPages}} 页，当前第 {{currentPage}} 页，每页 {{pageSize}} 条
          </div>
          <div class="pagination-buttons">
            <button @click="prevPage" :disabled="currentPage === 1" class="pagination-btn">上一页</button>
            <button
              v-for="page in pageRange"
              :key="page"
              @click="goToPage(page)"
              :class="{ 'pagination-btn': true, 'active': page === currentPage }"
            >
              {{ page }}
            </button>
            <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-btn">下一页</button>
          </div>
        </div>
      </div>
    </template>
  </CommonLayout>
</template>

<script setup lang="ts">
import CommonLayout from '../components/CommonLayout.vue';
import { ref, onMounted, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import moment from 'moment';
import { ElMessage } from 'element-plus';

// 定义商品接口类型
interface BrowseHistoryItem {
  history_id?: string | number;
  product_id: string | number;
  title: string;
  price: number;
  category_id: number;
  view_time: string;
  status: number;
  category_name?: string;
}

const router = useRouter();

// 分页相关状态
const currentPage = ref(1);
const totalPages = ref(1);
const pageSize = ref(10); // 每页显示10条数据

// 状态管理
const loading = ref<boolean>(false);
const products = ref<BrowseHistoryItem[]>([]);
const allCategories = ref<any[]>([]);

// 筛选表单数据
const filterForm = reactive<{
  keyword: string;
  categoryId: string;
  timeRange: string;
  sortByTime: string;
  sortByPrice: string;
  minPrice: number | '';
  maxPrice: number | '';
}>({
  keyword: '',
  categoryId: '',
  timeRange: 'all',
  sortByTime: '',
  sortByPrice: '',
  minPrice: '',
  maxPrice: ''
});

/**
 * 获取页码范围，用于显示分页按钮
 * @returns 页码数组
 */
const pageRange = computed(() => {
  const range = [];
  const maxVisiblePages = 5; // 最多显示5个页码按钮
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
  let endPage = startPage + maxVisiblePages - 1;

  if (endPage > totalPages.value) {
    endPage = totalPages.value;
    startPage = Math.max(1, endPage - maxVisiblePages + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    range.push(i);
  }

  return range;
});

/**
 * 跳转到上一页
 */
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchBrowseHistory();
  }
};

/**
 * 跳转到下一页
 */
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchBrowseHistory();
  }
};

/**
 * 跳转到指定页码
 * @param page 目标页码
 */
const goToPage = (page: number) => {
  if (page !== currentPage.value && page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
    fetchBrowseHistory();
  }
};

/**
 * 获取浏览历史
 */
const fetchBrowseHistory = async () => {
  loading.value = true;
  try {
    // 构建筛选参数
    const params: any = {
      page: currentPage.value,
      page_size: pageSize.value
    };

    if (filterForm.keyword) {
      params.keyword = filterForm.keyword;
    }

    if (filterForm.categoryId) {
      params.category_ids = filterForm.categoryId;
    }

    if (filterForm.timeRange !== 'all') {
      params.time_range = filterForm.timeRange;
    }

    if (filterForm.sortByTime) {
      params.sort_by = filterForm.sortByTime;
    } else if (filterForm.sortByPrice) {
      params.sort_by = filterForm.sortByPrice;
    }

    if (filterForm.minPrice !== '') {
      params.min_price = filterForm.minPrice;
    }

    if (filterForm.maxPrice !== '') {
      params.max_price = filterForm.maxPrice;
    }

    // 前端日志：记录请求参数
    console.log(`[${new Date().toISOString()}] [INFO] 浏览历史请求参数: ${JSON.stringify(params)}`);
    const token = localStorage.getItem('token');
    const res = await axios.get('/api/auth/browse-history', {
      params,
      headers: { 'Authorization': `Bearer ${token}` }
    });

    // 前端日志：记录响应结果
    console.log(`[${new Date().toISOString()}] [INFO] 浏览历史响应结果: ${JSON.stringify(res.data)}`);

    // 假设后端返回格式为 { success: true, data: { products: [], total_pages: 1 } }
    if (res.data && res.data.success && res.data.data && Array.isArray(res.data.data.products)) {
      // 数据验证，确保每个商品项都有必要的属性
      products.value = res.data.data.products.map((item: any) => {
        // 确保item是一个对象
        if (!item || typeof item !== 'object') {
          return {
            product_id: '',
            title: '未命名商品',
            price: 0,
            category_id: 0,
            view_time: '',
            status: 0
          } as BrowseHistoryItem;
        }

        return {
          ...item,
          product_id: item.product_id || item.id || '',
          title: item.title || '未命名商品',
          price: item.price !== undefined ? Number(item.price) : 0,
          category_id: item.category_id || 0,
          view_time: item.view_time || '',
          status: item.status !== undefined ? item.status : 0
        } as BrowseHistoryItem;
      });
      totalPages.value = res.data.data.total_pages || 1;
    } else {
      products.value = [];
      totalPages.value = 1;
    }
  } catch (err) {
    const e = err as any;
    console.error(`[${new Date().toISOString()}] [ERROR] 获取浏览历史异常:`, e);
    ElMessage.error((e.response && e.response.data && e.response.data.message) || '获取浏览历史失败');
    products.value = [];
  } finally {
    loading.value = false;
  }
};

/**
 * 获取分类列表
 */
const fetchCategories = async () => {
  try {
    console.log(`[${new Date().toISOString()}] [INFO] 请求分类列表`);
    const res = await axios.get('/api/product/categories');
    console.log(`[${new Date().toISOString()}] [INFO] 分类列表响应:`, res.data);

    if (res.data.categories && Array.isArray(res.data.categories)) {
      allCategories.value = res.data.categories;
    } else {
      allCategories.value = [];
    }
  } catch (err) {
    const e = err as any;
    console.error(`[${new Date().toISOString()}] [ERROR] 获取分类列表异常:`, e);
    allCategories.value = [];
  }
};

/**
 * 处理筛选提交
 */
const handleFilter = () => {
  // 重置页码为第一页
  currentPage.value = 1;
  fetchBrowseHistory();
};

/**
 * 重置筛选条件
 */
const resetFilter = () => {
  filterForm.keyword = '';
  filterForm.categoryId = '';
  filterForm.timeRange = 'all';
  filterForm.sortByTime = '';
  filterForm.sortByPrice = '';
  filterForm.minPrice = '';
  filterForm.maxPrice = '';
  currentPage.value = 1;
  fetchBrowseHistory();
};


/**
 * 查看商品详情
 * @param productId 商品ID
 * @param status 商品状态
 */
const viewProductDetail = (productId: number, status: number) => {
  if (status !== 1) {
    let message = '';
    switch(status) {
      case 0:
        message = '商品待审核';
        break;
      case 2:
        message = '商品已售';
        break;
      case 3:
        message = '商品已下架';
        break;
      default:
        message = '商品不可查看';
    }
    ElMessage.warning(message);
    return;
  }
  router.push(`/product/${productId}`);
};

/**
 * 格式化价格
 * @param price 价格
 * @returns 格式化后的价格字符串
 */
const formatPrice = (price: number) => {
  return price.toFixed(2);
};

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期字符串
 */
const formatDate = (dateString: string) => {
  return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
};

/**
 * 处理分类筛选变化事件
 * 重置页码并重新获取浏览历史
 */
const handleCategoryChange = () => {
  // 记录分类筛选日志
  console.log(`[${new Date().toISOString()}] [INFO] 分类筛选变更为: ${filterForm.categoryId}`);
  // 重置页码为第一页
  currentPage.value = 1;
  // 重新获取浏览历史
  fetchBrowseHistory();
};

// 页面加载时初始化数据
onMounted(() => {
  console.log(`[${new Date().toISOString()}] [INFO] [浏览历史] 组件已挂载，开始获取数据`);
  fetchCategories();
  fetchBrowseHistory();
});
</script>

<style scoped>
/* 复用商品管理页面的样式 */
.filter-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-input, .filter-select {
  width: 100%;
  padding: 8px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
}

.filter-btn {
  padding: 8px;
  background: #2563eb;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.reset-btn {
  padding: 8px;
  background: #f1f5f9;
  color: #334155;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.product-table-container {
  overflow-x: auto;
}

.product-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 600px;
}

.product-table th, .product-table td {
  padding: 12px 16px;
  text-align: left;
  vertical-align: middle;
}

.product-table th {
  background-color: #f8fafc;
  font-weight: 600;
  color: #334155;
}

.product-row:hover {
  background-color: #f8fafc;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}

.status-active {
  background-color: #dcfce7;
  color: #166534;
}

.status-pending {
  background-color: #fef3c7;
  color: #92400e;
}

.status-sold {
  background-color: #dbeafe;
  color: #1e40af;
}

.status-inactive {
  background-color: #fee2e2;
  color: #b91c1c;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-common {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

.btn查看 {
  background-color: #dbeafe;
  color: #1e40af;
}

.btn查看:disabled {
  background-color: #f1f5f9;
  color: #94a3b8;
  cursor: not-allowed;
}

/* 分页按钮样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px;
}

.pagination-info {
  color: #64748b;
  font-size: 14px;
}

.pagination-buttons {
  display: flex;
  gap: 8px;
}

.pagination-btn {
  padding: 6px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  background-color: white;
  color: #334155;
  cursor: pointer;
  font-size: 14px;
}

.pagination-btn:hover {
  background-color: #e2e8f0;
}

.pagination-btn:active {
  background-color: #cbd5e1;
}

.pagination-btn:disabled {
  background-color: #f1f5f9;
  color: #94a3b8;
  cursor: not-allowed;
}

.pagination-btn.active {
  background-color: #2563eb;
  color: white;
  border-color: #2563eb;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 6px;
}

.price-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  max-width: 94px; /* 限制最大宽度 */
}
</style>